/*
 * Copyright 2012 Claude Houle claude.houle@gmail.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.google.code.mochaccino.framework.smtp.client;

import com.google.common.base.Preconditions;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Writer;
import java.net.URL;
import java.util.UUID;
import sun.misc.BASE64Encoder;

/** Attachment Class */
public final class MessageAttachment {
	private InputStream source;
	private String      filename;
	private String      mimeType;

	/** Constructor */
	public MessageAttachment( String mimeType, String filename, InputStream source ) {
		this.mimeType = Preconditions.checkNotNull( mimeType, "No mime-type!" );
		this.filename = Preconditions.checkNotNull( filename, "No filename!" );
		this.source = Preconditions.checkNotNull( source, "No input!" );
	}

	/** Constructor */
	public MessageAttachment( String mimeType, String filename, byte[] source ) {
		this( mimeType, filename, new ByteArrayInputStream( source ) );
	}

	/** Constructor */
	public MessageAttachment( String mimeType, String filename, File source ) throws IOException {
		this( mimeType, filename, new BufferedInputStream( new FileInputStream( source ) ) );
	}

	/** Constructor */
	public MessageAttachment( String mimeType, String filename, URL source ) throws IOException {
		this( mimeType, filename, source.openStream() );
	}

	/** To SMTP Socket */
	public void toWriter( Writer out ) throws IOException {
		out.write( "Content-Type: " );
		out.write( mimeType );
		out.write( "; name=\"" );
		out.write( filename );
		out.write( "\"\n" );

		out.write( "Content-Disposition: attachment; filename=\"" );
		out.write( filename );
		out.write( "\"\n" );

		out.write( "Content-Transfer-Encoding: base64" );
		out.write( "\n" );

		out.write( "X-Attachment-Id: " );
		out.write( UUID.randomUUID().toString() );
		out.write( "\n" );
		out.write( "\n" );

		BASE64Encoder coder = new BASE64Encoder();
		byte[] block = new byte[64];
		int nbByte = -1;
		while ( (nbByte = source.read( block )) != -1 ) {
			String block64 = coder.encode( block );
			out.write( block64 );
			out.write( "\n" );
		}

		out.flush();
		source.close();
	}
}
